//
//  GoodsSearchViewController.m
//  LoveHappyShopping
//
//  Created by 白水非泉 on 16/6/26.
//  Copyright © 2016年 白水非泉. All rights reserved.
//

#import "GoodsSearchViewController.h"
#import <FMDatabase.h>
#import "GoodsSearchResultViewController.h"
@interface GoodsSearchViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)NSArray *hotLabelArray;
@property(nonatomic,strong)UIView *historyView;
@property(nonatomic,strong)UIView *hotView;
@property(nonatomic,strong)FMDatabase *db;
@property(nonatomic,strong)UITextField *navSearchText;
@property(nonatomic,strong)UILabel *noHistoryLabel;
@property(nonatomic,strong)UIImageView *hotImg;
@property(nonatomic,strong)UILabel *hotLabel;
@end

@implementation GoodsSearchViewController
-(FMDatabase *)db{
    if (!_db) {
        NSString *filePath=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"search.sqlite"];
        _db=[FMDatabase databaseWithPath:filePath];
        BOOL res=[_db open];
        if (res) {
            NSString *table=@"create table if not exists search(sid integer primary key autoincrement,content text not null)";
            [_db executeUpdate:table];
        }
    }
    return _db;
}
-(void)loadHistoryLabeFormDb{
    NSString *select=@"select content from search order by sid desc";
    FMResultSet *set=[self.db executeQuery:select];
    NSMutableArray *array=[NSMutableArray array];
    while (set.next) {
        NSString *content=[set stringForColumnIndex:0];
        [array addObject:content];
    }
    if (array.count) {
        [self.noHistoryLabel removeFromSuperview];
        [self addButtonToView:self.historyView WithArray:array];
    }
    else{
        self.historyView.height=30;
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 30)];
        label.text=@"暂无搜索历史";
        self.noHistoryLabel=label;
        label.textAlignment=NSTextAlignmentCenter;
        [self.historyView addSubview:label];
    }
    self.hotImg.y=CGRectGetMaxY(self.historyView.frame)+10;
    self.hotLabel.y=self.hotImg.y;
    self.hotView.y=CGRectGetMaxY(self.hotImg.frame)+10;
}
-(void)saveToDbWithContent:(NSString *)content{
    //    判断内容是否已经存在
    NSString *select=[NSString stringWithFormat:@"select content from search where content='%@'",content];
    //    NSString *
    FMResultSet *set=[self.db executeQuery:select];
    //    若存在
    if (set.next) {
        return;
    }
    NSString *insert=[NSString stringWithFormat:@"insert into search(content) values('%@')",content];
    [self.db executeUpdate:insert];
}
-(NSArray *)hotLabelArray{
    if (!_hotLabelArray) {
        _hotLabelArray=@[@"暑期游",@"电脑",@"夏季",@"运动",@"风扇",@"创意礼品",@"旅行",@"手机支架",@"收纳盒",@"厨房",@"拖鞋",@"卫浴",@"玩具",@"化妆礼品",@"衣架",@"沥水"];
    }
    return _hotLabelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout=UIRectEdgeNone;
    [self setNavBar];
    [self removeAllObject];
    [self.navSearchText becomeFirstResponder];
    [self searchLabelView];
    // Do any additional setup after loading the view.
}
-(void)removeAllObject{
    if (self.navSearchText.text!=nil) {
        
        for (id object in self.view.subviews) {
            [object removeFromSuperview];
        }
    }
}
-(void)setNavBar{
    UIButton *rightbtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 29, 14)];
    [rightbtn setBackgroundImage:[UIImage imageNamed:@"quxiao_btn"] forState:UIControlStateNormal];
    [rightbtn addTarget:self action:@selector(backToProView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightbtn];
    self.navigationItem.rightBarButtonItem=rightItem;
    
    UIImageView *leftImg=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 18, 20)];
    leftImg.image=[UIImage imageNamed:@"search_segment_glass"];
    UITextField *textFile=[[UITextField alloc]initWithFrame:CGRectMake(0, 0, SCREENW-80, 30)];
    textFile.returnKeyType=UIReturnKeySearch;
    [textFile addTarget:self action:@selector(nextSearchView:) forControlEvents:UIControlEventEditingDidEndOnExit];
    self.navSearchText=textFile;
    textFile.leftView=leftImg;
    textFile.leftViewMode=UITextFieldViewModeAlways;
    CALayer *layer=textFile.layer;
    layer.borderColor=[UIColor grayColor].CGColor;
    layer.borderWidth=1;
    layer.cornerRadius=2;
    
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc]initWithCustomView:textFile];
    self.navigationItem.leftBarButtonItem=leftItem;
    
    self.view.backgroundColor=[UIColor whiteColor];
}
-(void)nextSearchView:(UITextField *)textfiled{
    [self saveToDbWithContent:textfiled.text];
    [self searchResultViewWithString:textfiled.text];
}
-(void)searchResultViewWithString:(NSString *)sting{
    GoodsSearchResultViewController *searchResultVC=[[GoodsSearchResultViewController alloc]init];
    searchResultVC.searchText=sting;
    [self.navigationController pushViewController:searchResultVC animated:YES];
    
}
-(void)backToProView{
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden=NO;
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
}
-(void)searchLabelView{
    UIImageView *seachImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search_segment_glass"]];
    int imgX=20;
    int imgY=10;
    int imgW=24;
    int imgH=27;
    seachImg.frame=CGRectMake(imgX,imgY,imgW,imgH);
    int hlabX=CGRectGetMaxX(seachImg.frame)+5;
    int hlabY=imgY;
    int hlabW=100;
    int hlabH=imgH;
    UILabel *historyLabel=[[UILabel alloc]initWithFrame:CGRectMake(hlabX,hlabY, hlabW,hlabH)];
    historyLabel.text=@"最近搜索";
    int delY=imgY;
    int delW=imgW;
    int delH=imgH;
    int delX=SCREENW-delW-20;
    UIButton *delButton=[[UIButton alloc]initWithFrame:CGRectMake(delX, delY,delW,delH)];
    [delButton setBackgroundImage:[UIImage imageNamed:@"search_segment_del"] forState:UIControlStateNormal];
    [delButton addTarget:self action:@selector(deleteHistory) forControlEvents:UIControlEventTouchUpInside];
    
    int historyViewX=imgX;
    int historyViewY=CGRectGetMaxY(delButton.frame)+10;
    int historyViewW=SCREENW-40;
    
    UIView *historyView=[[UIView alloc]initWithFrame:CGRectMake(historyViewX, historyViewY, historyViewW, 100)];
    self.historyView=historyView;
    
    [self.view addSubview:seachImg];
    [self.view addSubview:historyLabel];
    [self.view addSubview:delButton];
    [self loadHistoryLabeFormDb];
    [self.view addSubview:historyView];
    
    int hotX=historyViewX;
    int hotY=CGRectGetMaxY(historyView.frame)+10;
    int hotW=imgW;
    int hotH=imgH;
    UIImageView *hotImg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search_segment_mark"]];
    self.hotImg=hotImg;
    hotImg.frame=CGRectMake(hotX,hotY,hotW,hotH);
    int hotlabX=CGRectGetMaxX(hotImg.frame)+5;
    int hotlabY=hotY;
    int hotlabW=100;
    int hotlabH=imgH;
    UILabel *hotLabel=[[UILabel alloc]initWithFrame:CGRectMake(hotlabX,hotlabY, hotlabW,hotlabH)];
    hotLabel.text=@"热门搜索";
    self.hotLabel=hotLabel;
    
    int hotViewX=imgX;
    int hotViewY=CGRectGetMaxY(hotLabel.frame)+10;
    int hotViewW=SCREENW-40;
    
    UIView *hotView=[[UIView alloc]initWithFrame:CGRectMake(hotViewX, hotViewY, hotViewW, 100)];
    self.hotView=hotView;
    [self addButtonToView:hotView WithArray:self.hotLabelArray];
    
    [self.view addSubview:hotImg];
    [self.view addSubview:hotLabel];
    [self.view addSubview:hotView];
}
-(void)deleteHistory{
    NSString *delete=@"delete from search";
    BOOL res=[self.db executeUpdate:delete];
    if (res) {
        for (UIButton *btn in self.historyView.subviews) {
            [btn removeFromSuperview];
        }
    }
    [self loadHistoryLabeFormDb];
    self.navSearchText.text=nil;
}
-(void)addButtonToView:(UIView *)view WithArray:(NSArray *)array {
    int btnX=0;
    int btnY=0;
    int btnW=80;
    int btnH=30;
    int margin=10;
    UIButton *lastBtn=nil;
    int row=0;
    for (NSString *str in array) {
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
        [btn setTitle:str forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn sizeToFit];
        btn.width+=10;
        if (lastBtn==nil) {
            btn.x=0;
        }
        else{
            btn.x=CGRectGetMaxX(lastBtn.frame)+margin;
        }
        if (btn.x+btn.width>view.width) {
            btn.x=0;
            row++;
        }
        btn.y=(margin+btnH)*row;
        lastBtn=btn;
        CALayer *layer=btn.layer;
        layer.borderColor=[UIColor grayColor].CGColor;
        layer.borderWidth=1;
        layer.cornerRadius=2;
        [btn addTarget:self action:@selector(searchBarContent:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:btn];
    }
    UIButton *lastestBtn=view.subviews.lastObject;
    view.height=CGRectGetMaxY(lastestBtn.frame);
}
-(void)searchBarContent:(UIButton *)btn{
    self.navSearchText.text=[btn currentTitle];
    
    NSString *delete=[NSString stringWithFormat:@"delete from search where content='%@'",btn.currentTitle];
    [self.db executeUpdate:delete];
    [self saveToDbWithContent:self.navSearchText.text];
    //    移除所有的按钮
    for (UIButton *button in self.historyView.subviews) {
        [button removeFromSuperview];
    }
    [self loadHistoryLabeFormDb];
    [self searchResultViewWithString:self.navSearchText.text];

}
#pragma marks - textfiled的代理方法
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
